package com.jci.vsd.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jci.vsd.R;
import com.jci.vsd.SlideRecycleview.CommonAdapter;
import com.jci.vsd.SlideRecycleview.SwipeMenuLayout;
import com.jci.vsd.SlideRecycleview.ViewHolder;
import com.jci.vsd.activity.LoginActivity;

import com.jci.vsd.activity.Reim.MyReimActivity;
import com.jci.vsd.activity.Reim.MyReimApprovalDetailActivity;
import com.jci.vsd.activity.Reim.ViewApprovalInfoActivity;
import com.jci.vsd.activity.enterprise.BudgetByCategoryManageActivity;
import com.jci.vsd.activity.enterprise.BudgetByDepartManageActivity;
import com.jci.vsd.activity.enterprise.MembsersManageActivity;
import com.jci.vsd.bean.MessageBean;

import com.jci.vsd.constant.AppConstant;
import com.jci.vsd.fragment.main.BaseFragment;
import com.jci.vsd.network.control.NoticeCenterControl;
import com.jci.vsd.network.control.ReimControl;
import com.jci.vsd.observer.CommonDialogObserver;
import com.jci.vsd.observer.DialogObserverHolder;
import com.jci.vsd.observer.RxHelper;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.view.widget.SimpleToast;

import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * Created by liqing on 18/6/28.
 *
 */

public class MessageFragment extends BaseFragment implements DialogObserverHolder {

    private Context context;

    private List<MessageBean> mData;

    private CommonAdapter<MessageBean> mAdapter;
    private LinearLayoutManager mLayoutManager;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView mRecyclerView;

    Boolean isSetSuccessFul;


    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container, false);
        context = MessageFragment.this.getActivity();
        mData = new ArrayList<>();
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rl_approving);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 1500);
            }
        });


        mAdapter = new CommonAdapter<MessageBean>(context, mData, R.layout.item_message_swipe) {
            @Override
            public void convert(final ViewHolder holder, MessageBean bean) {
                ((SwipeMenuLayout) holder.itemView).setIos(true).setLeftSwipe(true);

                RelativeLayout rlItemMsg = (RelativeLayout) holder.getView(R.id.rl_item_msg);

                //     LinearLayout llState = (LinearLayout) holder.getView(R.id.ll_unread);
                TextView tvStateCircle = (TextView) holder.getView(R.id.tv_unread_circle);
                TextView tvStateText = (TextView) holder.getView(R.id.tv_unread_text);

                TextView tvMsgTitle = (TextView) holder.getView(R.id.tv_unread_title);

                TextView tvMsgContent = (TextView) holder.getView(R.id.tv_unread_content);

                TextView tvMsgTime = (TextView) holder.getView(R.id.tv_unread_time);
                final Boolean isRead = bean.isIsRead();

                if (isRead != null) {
                    if (isRead) {
                        //已读
                        tvStateCircle.setBackgroundResource(R.drawable.circle_grey);
                        tvStateText.setText("已读");
                        tvStateText.setTextColor(context.getResources().getColor(R.color.gray_B3B3B3));
                    } else {
                        //未读

                        tvStateCircle.setBackgroundResource(R.drawable.circle_blue);
                        tvStateText.setText("未读");
                        tvStateText.setTextColor(context.getResources().getColor(R.color.bg_tab_select_blue));
                    }
                }
                tvMsgTitle.setText(bean.getTitle());
                tvMsgContent.setText(bean.getContext());
                tvMsgTime.setText(bean.getCreateTime());

                holder.setOnClickListener(R.id.btnDelete, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getLayoutPosition();
                        if (pos >= 0 && pos < mDatas.size()) {

                            delete(mDatas.get(pos).getId(), pos);

                            //如果删除时，不使用mAdapter.notifyItemRemoved(pos)，则删除没有动画效果，
                            //且如果想让侧滑菜单同时关闭，需要同时调用 ((SwipeMenuLayout) holder.itemView).quickClose();
                            //mAdapter.notifyDataSetChanged();
                        }
                    }
                });

                //注意事项，设置item点击，不能对整个holder.itemView设置咯，只能对第一个子View，即原来的content设置，这算是局限性吧。
                (holder).setOnClickListener(R.id.content, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getLayoutPosition();
                        int id = mData.get(pos).getId();
                        String intentId = String.valueOf(id);
                        int typeMsg = mData.get(pos).getType();
                        Boolean isReaded = mData.get(pos).isIsRead();
                        Loger.e("----");
                        if (!isReaded) {
                            setMsgReaded(id);
                        }

                        //test
                        //  typeMsg = 5;

                        if (typeMsg == 1) {
                            //1 提醒审批者，有新的报销单待审批
                            //  toActivityWithId(MessageFragment.this,intentId,MyApprovalRecyActivity.class,intentId );
                            toActivityWithId(MessageFragment.this, ViewApprovalInfoActivity.class, intentId);

                        }
                        if (typeMsg == 2) {
                            //2 提醒报销，审批结果已出
                            toActivityWithData(MessageFragment.this, MyReimActivity.class, AppConstant.KEY_TYPE, "msg");

                        }
                        if (typeMsg == 3) {
                            //3 提醒boss ，有新员工加入
                            toActivityWithId(MessageFragment.this, MembsersManageActivity.class, intentId);
                        }


                        //4 预算超出提醒

                        if (typeMsg == 4 || typeMsg == 6) {
                            //4 提醒 ，部门预算超出提醒
//                            if (!isReaded) {
//                                setMsgReaded(id);
//                            }
//                            getData();

                            // mAdapter.notifyItemRemoved(pos);//推荐用这个

                            toActivity(MessageFragment.this, BudgetByDepartManageActivity.class);

                        }
                        //5 角色改变提醒

                        if (typeMsg == 5) {
                            //5 提醒 ，变为主管，请重新登录
                            toActivity(MessageFragment.this, LoginActivity.class);
                            getActivity().finish();


                        }

//                        if (typeMsg == 6) {
//                            if (!isReaded) {
//                                setMsgReaded(id);
//                            }
//                            mAdapter.notifyDataSetChanged();
//                            //6 提醒 ，科目预算超出提醒
//                          //  toActivity(MessageFragment.this, BudgetByCategoryManageActivity.class);
//                        }


//                        if( setMsgReaded(id)!=null&&setMsgReaded(id)){
//
//hash table  linked list implement of the Map interface with predicatable iterator order.
// this implement differs form HashTable in that it maintained double-linked list running throught all its entries
//this linked list defines the the iteration odering,which is nomally the order in which
// keys were insered into the map(insertion order);


//                        }


                        Log.d("TAG", "onClick() called with: v = [" + v + "]");
                    }
                });

                //验证长按
                holder.setOnLongClickListener(R.id.content, new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        Toast.makeText(mContext, "longclig", Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onLongClick() called with: v = [" + v + "]");
                        return false;
                    }
                });

            }
        };

        //setDapter

        mRecyclerView.setAdapter(mAdapter);
        //mRecyclerView.setLayoutManager(mLayoutManager = new GridLayoutManager(getContext(), 2));
        mRecyclerView.setLayoutManager(mLayoutManager = new LinearLayoutManager(getContext()));

        //6 2016 10 21 add , 增加viewChache 的 get()方法，
        // 可以用在：当点击外部空白处时，关闭正在展开的侧滑菜单。我个人觉得意义不大，
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    SwipeMenuLayout viewCache = SwipeMenuLayout.getViewCache();
                    if (null != viewCache) {
                        viewCache.smoothClose();
                    }
                }
                return false;
            }
        });
        return view;
    }


    private Boolean setMsgReaded(int intentId) {
        Observable<Boolean> observable = new NoticeCenterControl().setMsgReaded(intentId);
        CommonDialogObserver<Boolean> observer = new CommonDialogObserver<Boolean>(this) {
            @Override
            public void onNext(Boolean boo) {
                super.onNext(boo);
                isSetSuccessFul = boo;

            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
            }
        };
        RxHelper.bindOnUI(observable, observer);
        return isSetSuccessFul;
    }

    private void initDatas() {
        for (int i = 0; i < 5; i++) {
            MessageBean bean = new MessageBean();
            //  bean.setDate("2018-01-07");
            mData.add(i, bean);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // getData(type);
        getData();

    }

    private void getData() {
        Observable<List<MessageBean>> observable = new NoticeCenterControl().getMessages();
        CommonDialogObserver<List<MessageBean>> observer = new CommonDialogObserver<List<MessageBean>>(this) {
            @Override
            public void onNext(List<MessageBean> list) {
                super.onNext(list);
                if (list.size() == 0) {
                    SimpleToast.toastMessage("暂无消息", Toast.LENGTH_SHORT);
                } else {
                    //SimpleToast.toastMessage("数据获取成功", Toast.LENGTH_SHORT);
                }


                mData.clear();
                mData.addAll(list);
                mAdapter.notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                if (t.getMessage().equals("401")) {
                    SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_SHORT);
                    toActivity(MessageFragment.this, LoginActivity.class);
                    getActivity().finish();
                }
            }
        };
        RxHelper.bindOnUI(observable, observer);

    }

    private void delete(int id, final int pos) {


        Observable<Boolean> observable = new NoticeCenterControl().deleteMsg(id);
        CommonDialogObserver<Boolean> observer = new CommonDialogObserver<Boolean>(this) {
            @Override
            public void onNext(Boolean isSuccess) {
                super.onNext(isSuccess);
                SimpleToast.toastMessage("删除成功", Toast.LENGTH_SHORT);
                mData.remove(pos);
                mAdapter.notifyItemRemoved(pos);//推荐用这个


            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                if (t.getMessage().equals("401")) {
                    SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_SHORT);

                }


            }


        };
        RxHelper.bindOnUI(observable, observer);

    }


    @Override
    public void addDisposable(Disposable disposable) {

    }

    @Override
    public void addSubscription(Subscription subscription) {

    }

    @Override
    public void removeDisposable(Disposable disposable) {

    }

    @Override
    public FragmentManager getSupportFragmentManager() {
        return getActivity().getSupportFragmentManager();
    }
}
